<!--
 * @Author: wangshuguang
 * @Date: 2022-02-17 20:23:25
 * @LastEditTime: 2022-02-18 09:36:49
 * @LastEditors: wangshuguang
 * @Description: 密码输入框
-->
<template>
  <div :id="`ids_${id}`" class="am-payPwd">
    <input
      v-for="(v, i) in 6"
      :key="i"
      v-model="pwdList[i]"
      type="password"
      readonly
      onfocus="this.removeAttribute('readonly');"
      maxlength="1"
      autocomplete="new-password"
      class="shortInput"
      @input="changeInput"
      @click="changePwd"
      @keyup="keyUp($event)"
      @keydown="oldPwdList = pwdList.length"
    >
  </div>
</template>
<script>
export default {
  props: {
    id: {
      type: Number,
      default: 1 // 当一个页面有多个密码输入框时，用id来区分
    }
  },
  data() {
    return {
      pwdList: [],
      oldPwdList: [],
      isDelete: false,
      ipt: ''
    }
  },
  mounted() {
    this.ipt = document.querySelectorAll(`#ids_${this.id} .shortInput`)
  },
  methods: {
    keyUp(ev) {
      let index = this.pwdList.length
      if (!index) return
      if (ev.keyCode === 8) {
        this.isDelete = true
        if (this.oldPwdList === this.pwdList.length) {
          if (index === this.pwdList.length) {
            this.pwdList.pop()
          }
          index--
        } else {
          index > 0 && index--
        }
        this.ipt[index].focus()
      } else if (this.isDelete && index === this.pwdList.length && /^\d$/.test(ev.key)) {
        this.isDelete = false
        this.pwdList.pop()
        this.pwdList.push(ev.key)
        this.ipt[this.pwdList.length] && this.ipt[this.pwdList.length].focus()
      }
      this.$emit('getPwd', this.pwdList.join(''))
    },
    changePwd() {
      let index = this.pwdList.length
      index === 6 && index--
      this.ipt[index].focus()
    },
    changeInput() {
      let index = this.pwdList.length
      const val = this.pwdList[index - 1]
      if (!/[0-9]/.test(val)) {
        this.pwdList.pop()
        return
      }
      if (!val) {
        this.pwdList.pop()
        index--
        if (index > 0) this.ipt[index - 1].focus()
      } else {
        if (index < 6) this.ipt[index].focus()
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
    .am-payPwd {
        display: inline-block;
        border-radius: 5px;
        padding: 10px 0;
        border: 1px solid #cccccc;
        position: relative;
        margin-left: 1px;
        .shortInput {
          border: none;
          text-align: center;
          font-size: 30px;
          float: left;
          width: 40px;
          height: 20px !important;
          color: #333;
          outline: #ff0067;
          border-right: 1px solid #eee;
          &:last-child{
              border-right:0;
            }
        }
    }
</style>
